package com.xpmusic.controller.admin;

import com.xpmusic.dao.impl.MusicDaoImpl;
import com.xpmusic.model.MusicInfo;
import com.xpmusic.util.MP3InfoUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/uploadMusicServlet")
public class UploadMusicServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        /**
         * 判断是否是表单数据
         */
        boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
        if(!isMultipartContent){
            throw new RuntimeException("非表单数据，禁止上传!");
        }

        try {
            //创建文件磁盘工厂
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            servletFileUpload.setHeaderEncoding("utf-8");
            //上传进度
            servletFileUpload.setProgressListener(new ProgressListener() {
                public void update(long pBytesRead, long pContentLength, int pItems) {
                    System.out.println("文件大小：" + pContentLength + ",当前已经处理：" +  pBytesRead);
                }
            });
            //表单中的每一组上传数据作为一个list子集
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            //遍历fileItem
            for (FileItem fileItem : fileItems) {
                //判断当数据是文件数据，即非表单数据
                if(!fileItem.isFormField()){
                    //上传文件
                    processUploadField(fileItem , request, response);
                }
            }
            //上传完文件重定向回到原界面
            response.sendRedirect("musicList.jsp");
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

    /**
     * 上传文件
     * @param fileItem
     */
    private void processUploadField(FileItem fileItem, HttpServletRequest request, HttpServletResponse response) {
        MusicInfo musicInfo = new MusicInfo();
        String fileName = fileItem.getName();

        String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
        if(!fileExtName.equals("mp3")){
            request.getSession().setAttribute("illegalFile","非法文件！");
            return;
        }

        System.out.println(fileName);

        try {
            //得到文件输入流
            InputStream inputStream = fileItem.getInputStream();
            //创建一个文件存盘目录
            String directoryRealPath = this.getServletContext().getRealPath("/music");
            File storeDirectory = new File(directoryRealPath);//即表示文件也表示目录
            if(!storeDirectory.exists()){
                storeDirectory.mkdirs();//创建一个指定的目录
            }
            //storyDirectory下，创建完整目录下的文件
            File file = new File(storeDirectory, fileName);
            //通过文件输出流将上传的文件保存到磁盘
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            int len = 0;
            byte[] b = new byte[1024];
            while((len = inputStream.read(b)) != -1){
                fileOutputStream.write(b, 0 , len);
            }
            fileOutputStream.close();
            inputStream.close();
            //删除上传产生的临时文件
            fileItem.delete();

            String path = this.getServletContext().getRealPath("/music/");

            //上传的文件名格式为 XX - YY.mp3  需要将前面XX的歌手名提取出来，后面YY歌曲名提取出来，YY.mp3歌曲名提取出来
            String[] singer = fileName.split("-");//将XX歌手名提取出来
            String[] musicName = singer[1].split(".mp3");//将YY歌名提取出来
            musicInfo.setSinger(singer[0]);
            musicInfo.setMusicName(musicName[0]);//将歌曲名YY.mp3提取出来
            musicInfo.setMusicPath("./music/"+fileName);

            //File mp3File = new File(path + fileName);
            //MP3InfoUtil mp3Info = new MP3InfoUtil(mp3File);
            //mp3Info.setCharset("GBK");
            //musicInfo.setMusicInfo(mp3Info.getAlbum());

            //向数据库中添加歌曲信息
            new MusicDaoImpl().uploadMusic(musicInfo);
            //输出music信息
            System.out.println(musicInfo.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
